import Navbar from "@/components/Navbar";
import { observer } from "mobx-react-lite";
import { Image, Text, View } from "@tarojs/components";
import systemStore from "@/stores/SystemStore";
import "./index.less";
import ButtonComp from "@/components/Button";
import leaseStore from "@/stores/LeaseStore";
import { LeaseEntity } from "@/entities/LeaseEntity";
import { CommonUtil } from "@/utils/CommonUtil";
import BusinessConstant from "@/constant/BusinessConstant";
import HouseLeaseBusiness from "@/business/HouseLeaseBusiness";
import { useState } from "react";
import AlterComp from "@/components/Alter";
import Forbid from "@/static/images/icon/forbid.png";
import socketStore from "@/stores/SocketStore";
import AuthConstant from "@/constant/AuthConstant";
import useLandlord from "@/hooks/useLandlord";
import useHouse from "@/hooks/useHouse";
import TenantCard from "@/components/TenantCard";

function LeaseNotice() {
  const { getTenantsByLandlordId } = useLandlord();
  const { againGetLandlordHouseList } = useHouse();
  const { pendingLeaseList, setPendingLeaseList } = leaseStore;
  const { websocketInstance } = socketStore;
  const [leasePopupVisible, setLeasePopupVisible] = useState(false);
  const [currentLease, setCurrentLease] = useState<LeaseEntity.IPendingLease>();
  const [currentStatus, setCurrentStatus] = useState<number>();
  const [alterText, setAlterText] = useState("");

  /**
   * 改变租赁的状态
   */
  const changeLeaseStatus = async () => {
    await HouseLeaseBusiness.updateLeaseStatus({
      status: currentStatus!,
      landlordId: currentLease?.landlordId!,
      tenantId: currentLease?.tenantId!,
      houseId: currentLease?.houseId!,
    });
    const pendingLeaseList: any =
      await HouseLeaseBusiness.getTenantLeasePendingTodoByLandlordId();
    setPendingLeaseList(pendingLeaseList);
    setLeasePopupVisible(false);
    // 通过租赁
    if (currentStatus === BusinessConstant.LEASE_TRAVERSE) {
      // 通知该租客的首页进行租赁房屋数据刷新
      websocketInstance &&
        websocketInstance.send({
          data: JSON.stringify({
            toIdentity: AuthConstant.TENANT,
            toId: currentLease?.tenantId!,
            active: BusinessConstant.SOCKET_GET_TENANT_LEASE_HOUSE,
          }),
        });
      // 更新该房东的租客信息（人数）
      getTenantsByLandlordId();
      // 更新该房东的房屋
      againGetLandlordHouseList();
    }
  };

  const showLeasePopup = (lease: LeaseEntity.IPendingLease, status: number) => {
    if (status === BusinessConstant.LEASE_TRAVERSE) {
      setAlterText("是否通过申请？租客将直接入住房屋！");
    } else if (status === BusinessConstant.LEASE_REJECT) {
      setAlterText("是否驳回申请？");
    }
    setLeasePopupVisible(true);
    setCurrentLease(lease);
    setCurrentStatus(status);
  };

  return (
    <Navbar title="租赁申请" mode="back" bgColor="var(--mini-first)">
      <View
        className="lease-notice-container"
        style={{ height: systemStore.haveNavbarNotTabbarHeight }}
      >
        {pendingLeaseList.length !== 0 ? (
          pendingLeaseList.map(
            (lease: LeaseEntity.IPendingLease, idx: number) => {
              return (
                <TenantCard
                  key={idx}
                  lease={lease}
                  msgItemNode={
                    <>
                      <View className="lease-item">
                        <Text>申请租赁时长：</Text>
                        <Text>{lease.leaseMonths}个月</Text>
                      </View>
                      <View className="lease-item">
                        <Text>申请日期：</Text>
                        <Text>{CommonUtil.formatUtcTime(lease.leaseDate)}</Text>
                      </View>
                    </>
                  }
                  bottomNode={
                    <View className="btn-group">
                      <ButtonComp
                        title="通过申请"
                        size="middle"
                        onClick={() =>
                          showLeasePopup(lease, BusinessConstant.LEASE_TRAVERSE)
                        }
                      />
                      <ButtonComp
                        title="驳回申请"
                        bgColor="var(--mini-fifth)"
                        size="middle"
                        onClick={() =>
                          showLeasePopup(lease, BusinessConstant.LEASE_REJECT)
                        }
                      />
                    </View>
                  }
                />
              );
            }
          )
        ) : (
          <View className="no-lease-application">
            <Image src={Forbid} className="forbid-icon" />
            <Text>暂无租赁申请</Text>
          </View>
        )}
        <AlterComp
          visible={leasePopupVisible}
          onClose={() => setLeasePopupVisible(false)}
          onConfirm={changeLeaseStatus}
          content={alterText}
        />
      </View>
    </Navbar>
  );
}

export default observer(LeaseNotice);
